package com.mzj.saas.mservice.eligible.service;

import cn.hutool.core.collection.CollectionUtil;
import com.mzj.saas.commons.*;
import com.mzj.saas.commons.enums.*;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.application.entity.ApprovalProcessUser;
import com.mzj.saas.mservice.application.repository.ApprovalProcessUserRepository;
import com.mzj.saas.mservice.area.entity.Area;
import com.mzj.saas.mservice.area.repository.AreaRepository;
import com.mzj.saas.mservice.backlog.entity.BacklogItem;
import com.mzj.saas.mservice.backlog.entity.BacklogItemApprove;
import com.mzj.saas.mservice.backlog.entity.BacklogItemRent;
import com.mzj.saas.mservice.backlog.entity.BacklogItemWaitRent;
import com.mzj.saas.mservice.backlog.repository.BacklogItemApproveRepository;
import com.mzj.saas.mservice.backlog.repository.BacklogItemRentRepository;
import com.mzj.saas.mservice.backlog.repository.BacklogItemRepository;
import com.mzj.saas.mservice.backlog.repository.BacklogItemWaitRentRepository;
import com.mzj.saas.mservice.community.entity.Community;
import com.mzj.saas.mservice.community.repository.CommunityRepository;
import com.mzj.saas.mservice.department.entity.Department;
import com.mzj.saas.mservice.department.repository.DepartmentRepository;
import com.mzj.saas.mservice.eligible.entity.*;
import com.mzj.saas.mservice.eligible.repository.*;
import com.mzj.saas.mservice.eligible.vo.*;
import com.mzj.saas.mservice.house.entity.Cohabit;
import com.mzj.saas.mservice.house.entity.House;
import com.mzj.saas.mservice.house.entity.HouseMatchUser;
import com.mzj.saas.mservice.house.repository.CohabitRepository;
import com.mzj.saas.mservice.house.repository.HouseMatchUserRepository;
import com.mzj.saas.mservice.house.repository.HouseRepository;
import com.mzj.saas.mservice.house.service.HouseService;
import com.mzj.saas.mservice.house.vo.HouseInfoVO;
import com.mzj.saas.mservice.lock.Repository.*;
import com.mzj.saas.mservice.lock.entity.SmartLock;
import com.mzj.saas.mservice.lock.entity.SmartLockAuth;
import com.mzj.saas.mservice.lock.service.LockAppService;
import com.mzj.saas.mservice.records.entity.HousePutRecords;
import com.mzj.saas.mservice.records.repository.HousePutRecordsRepository;
import com.mzj.saas.mservice.sms.service.SmsService;
import com.mzj.saas.mservice.sys.entity.AppUser;
import com.mzj.saas.mservice.sys.repository.AppUserRepository;
import com.mzj.saas.mservice.sys.service.AppUserService;
import com.mzj.saas.mservice.sys.utils.SqlUtils;
import com.mzj.saas.redis.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ApproveService {
    private static final Logger log = LoggerFactory.getLogger(ApproveService.class);

    private static final String APPROVE_COUNT = "SELECT COUNT(1) ";
    private static final String APPROVE_COLUM = "SELECT a.`id`,a.`match_user_id` AS matchUserId,a.`apply_status` AS applyStatus,\n" +
            "a.`match_status` AS matchStatus,a.district_id as districtId,a.`community_id` AS communityId,a.`apply_time` AS apply_time,a.name";
    private static final String APPROVE_FROM_MONITOR = " FROM saas_house_eligible_apply a ";
    private static final String ORDER_ORDER = " ORDER BY a.apply_time DESC";
    private static final String SQL_PAGE = " LIMIT ? OFFSET ?";

    private static final String APPROVE_COLUM2 = "SELECT a.`id`,a.`match_user_id` AS matchUserId,a.`apply_status` AS applyStatus,\n" +
            "a.`match_status` AS matchStatus,a.district_id as districtId,a.`community_id` AS communityId,a.`apply_time` AS apply_time,a.name,a.dataType";
    private static final String APPROVE_FROM_MONITOR2 = " FROM (SELECT a.*,1 AS dataType\n" +
            "FROM saas_house_eligible_apply a \n" +
            "UNION ALL \n" +
            "SELECT a.*,2 AS dataType\n" +
            "FROM saas_house_eligible_apply_old a) a ";

    @Autowired
    private RedisService redisService;
    @Autowired
    private ApplyAuditRepository applyAuditRepository;
    @Autowired
    private HouseRepository houseRepository;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private AppUserService appUserService;
    @Autowired
    private WaitingRentRecordRepository waitingRentRecordRepository;
    @Autowired
    private EligibleRepository eligibleRepository;
    @Autowired
    private AppUserRepository appUserRepository;
    @Autowired
    private DepartmentHierarchyRepository departmentHierarchyRepository;
    @Autowired
    private DepartmentEnterpriseTagRefRepository departmentEnterpriseTagRefRepository;
    @Autowired
    private BacklogItemRepository backlogItemRepository;
    @Autowired
    private BacklogItemRentRepository backlogItemRentRepository;
    @Autowired
    private BacklogItemApproveRepository backlogItemApproveRepository;
    @Autowired
    private BacklogItemWaitRentRepository backlogItemWaitRentRepository;
    @Autowired
    private SmartLockAuthRepository smartLockAuthRepository;
    @Autowired
    private HousePutRecordsRepository housePutRecordsRepository;
    @Autowired
    private CohabitRepository cohabitRepository;
    @Autowired
    private SmartLockRepository smartLockRepository;
    @Autowired
    private AreaRepository areaRepository;
    @Autowired
    private HouseMatchUserRepository houseMatchUserRepository;
    @Autowired
    private HouseService houseService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private LockAppService lockAppService;
    @Autowired
    private SmartLockPwdRepository smartLockPwdRepository;
    @Autowired
    private SmartLockCardRepository smartLockCardRepository;
    @Autowired
    private SmartLockFingerprintRepository smartLockFingerprintRepository;
    @Autowired
    private HouseApplyFlowRepository houseApplyFlowRepository;
    @Autowired
    private CommunityRepository communityRepository;
    @Autowired
    private DepartmentRepository departmentRepository;
    @Autowired
    private ApplyAuditOldRepository applyAuditOldRepository;
    @Autowired
    private ApprovalProcessUserRepository approvalProcessUserRepository;

    public ResultBean<EligibleApiData<EligibleListVO>> eligibleList(String accessToken, Integer status,
                                                                    Integer pageNumber, Integer pageSize) {
        ResultBean<EligibleApiData<EligibleListVO>> resultBean = new ResultBean<>();
        resultBean.setCode("10000");
        resultBean.setMsg("10000");
        EligibleApiData<EligibleListVO> apiData = new EligibleApiData<>();
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            AppUser user = appUserService.findByIdAndStatus(userId, 1, tokenRedisVo.getLoginType());
            if (user == null) {
                return ResultBean.failedResultWithMsg("用户不存在");
            }
            Long enterpriseId = tokenRedisVo.getEnterpriseId();
            if (enterpriseId == null) {
                return ResultBean.failedResultWithMsg("非企业用户");
            }

            DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
            if (hierarchy == null) {
                return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
            }
            Long id = hierarchy.getId();
            List<DepartmentEnterpriseTagRef> refs = departmentEnterpriseTagRefRepository.findByDepRefId(id);
            List<Long> enterpriseTagIds = refs.stream().map(DepartmentEnterpriseTagRef::getTagId).distinct().collect(Collectors.toList());// 用户企业标签

            Long areaTagId = hierarchy.getTagId();// 区域标签
            Long areaId = hierarchy.getAreaId();// 区域id
            String areaTag = "province_id";
            if (areaTagId == 1) {
                areaTag = "province_id";
            } else if (areaTagId == 2) {
                areaTag = "city_id";
            } else if (areaTagId == 3) {
                areaTag = "district_id";
            } else if (areaTagId == 4) {
                areaTag = "street_id";
            } else if (areaTagId == 5) {
                areaTag = "community_id";
            }

            if (status == null) {
                return ResultBean.failedResultOfParamWithMsg("status为空");
            }

            // 待审批总数
            List<ApplyAudit> audits = applyAuditRepository.findByAuditStatusAndCurrentAuditId(1, userId);
            List<Long> applyIds = audits.stream().filter(vo -> vo.getApplyId() != null).map(ApplyAudit::getApplyId).distinct().collect(Collectors.toList());

            List<Object> yetApproveArgs = new ArrayList<>();
            StringBuilder yetApproveWhere = new StringBuilder();
            yetApproveWhere.append(" where a.apply_status in (1,2,10) and a.id in ");

            Long yetApproveTotal = 0L;
            if (applyIds != null && !applyIds.isEmpty()) {
                yetApproveWhere.append(SqlUtils.foreachIn(applyIds.size()));
                yetApproveArgs.addAll(applyIds);
                yetApproveTotal = jdbcTemplate.queryForObject(APPROVE_COUNT + APPROVE_FROM_MONITOR2 + yetApproveWhere, yetApproveArgs.toArray(), Long.class);
            }

            List<Object> totalArgs = new ArrayList<>();
            totalArgs.add(areaId);
            // 轮候配租总数
            Long waitRentTotal = 0L;
            // 待配租总数
            Long yetRentTotal = 0L;
            // 已完成总数
            Long doneTotal = 0L;
            if (enterpriseTagIds.contains(5L) || enterpriseTagIds.contains(2L)) {
                waitRentTotal = jdbcTemplate.queryForObject(APPROVE_COUNT + APPROVE_FROM_MONITOR2 + " where a." + areaTag + " = ? and a.apply_status = 3 and a.match_status = 1", totalArgs.toArray(), Long.class);
            }
            if (enterpriseTagIds.contains(5L) || enterpriseTagIds.contains(2L)) {
                yetRentTotal = jdbcTemplate.queryForObject(APPROVE_COUNT + APPROVE_FROM_MONITOR2 + " where a." + areaTag + " = ? and a.apply_status = 3 and a.match_status = 2", totalArgs.toArray(), Long.class);
            }
            doneTotal = jdbcTemplate.queryForObject(APPROVE_COUNT + APPROVE_FROM_MONITOR2 + " where a." + areaTag + " = ? and a.apply_status = 3 and a.match_status = 3", totalArgs.toArray(), Long.class);

            apiData.setYetApproveTotal(yetApproveTotal);
            apiData.setWaitRentTotal(waitRentTotal);
            apiData.setYetRentTotal(yetRentTotal);
            apiData.setDoneTotal(doneTotal);
            resultBean.setResultData(apiData);

            StringBuilder where = new StringBuilder();
            List<Object> args = new ArrayList<>();
            where.append(" where 1 = 1");
            // 待审批：当前审批节点是自己。
            if (status == 1) {
                where.append(" and a.apply_status in (1,2,10) and a.id in ");
                if (applyIds != null && !applyIds.isEmpty()) {
                    where.append(SqlUtils.foreachIn(applyIds.size()));
                    args.addAll(applyIds);
                } else {
                    return resultBean;
                }
            }

            // 轮候配租：住建局、产权单位，根据企业所在区域过滤
            if (status == 2) {
                if (enterpriseTagIds.contains(5L) || enterpriseTagIds.contains(2L)) {
                    where.append(" and a." + areaTag + " = ? and a.apply_status = 3 and a.match_status = 1");
                    args.add(areaId);
                } else {
                    return resultBean;
                }
            }

            // 待配租：住建局、产权单位
            if (status == 3) {
                if (enterpriseTagIds.contains(5L) || enterpriseTagIds.contains(2L)) {
                    where.append(" and a." + areaTag + " = ? and a.apply_status = 3 and a.match_status = 2");
                    args.add(areaId);
                } else {
                    return resultBean;
                }
            }

            // 已完成：所有用户
            if (status == 4) {
                where.append(" and a." + areaTag + " = ? and a.apply_status = 3 and a.match_status = 3");
                args.add(areaId);
            }

            // 当前条件总数
            Long total = jdbcTemplate.queryForObject(APPROVE_COUNT + APPROVE_FROM_MONITOR2 + where, args.toArray(),
                    Long.class);
            if (total == 0) {
                return resultBean;
            }

            args.add(pageSize);
            args.add(pageNumber * pageSize);
            List<EligibleListVO> eligibleList = jdbcTemplate.query(APPROVE_COLUM2 + APPROVE_FROM_MONITOR2 + where + ORDER_ORDER + SQL_PAGE,
                    new BeanPropertyRowMapper<>(EligibleListVO.class), args.toArray());

            for (EligibleListVO vo : eligibleList) {
                SimpleDateFormat sformat = new SimpleDateFormat(DateUtils.FORMAT_DATETIME_14);
                vo.setApplyTime(DateUtils.format(sformat.parse(vo.getApplyTime()), DateUtils.FORMAT_DATETIME_14));
            }

            // 查询申请人名称
            List<String> ids = eligibleList.stream().filter(vo -> vo.getMatchUserId() != null)
                    .map(EligibleListVO::getMatchUserId).distinct().collect(Collectors.toList());
            if (!ids.isEmpty()) {
                List<AppUser> appUsers = appUserRepository.findByIdOrEnterpriseIn(ids, ids);
                for (AppUser appUser : appUsers) {
                    for (EligibleListVO vo : eligibleList) {
                        if (vo.getMatchUserId() != null && (vo.getMatchUserId().equals(appUser.getId()) || vo.getMatchUserId().equals(appUser.getEnterpriseUserId()))) {
                            vo.setMatchUserName(appUser.getName());
                        }
                    }
                }
            }

            apiData.setData(eligibleList);
            apiData.setTotal(total);

            resultBean.setResultData(apiData);
        } catch (Exception e) {
            log.error("ApproveService eligibleList Exception = {}" + e.getMessage(), e);
            resultBean.setCode("10001");
            resultBean.setMsg("10001");
        }
        resultBean.setResultData(apiData);
        return resultBean;
    }

    /*public ResultBean<ApiData<EligibleListVO>> eligibleList2(String accessToken, String name, Integer type, String applyArea,
                                                             Integer applyStatus, Integer matchStatus, Integer pageNumber, Integer pageSize) {
        ResultBean<ApiData<EligibleListVO>> resultBean = new ResultBean<>();
        resultBean.setCode("10000");
        resultBean.setMsg("10000");
        ApiData<EligibleListVO> apiData = new ApiData<>();
        resultBean.setResultData(apiData);
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            Long enterpriseId = tokenRedisVo.getEnterpriseId();

            DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
            if (hierarchy == null) {
                return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
            }
            Long id = hierarchy.getId();
            List<DepartmentEnterpriseTagRef> refs = departmentEnterpriseTagRefRepository.findByDepRefId(id);
            List<Long> enterpriseTagIds = refs.stream().map(DepartmentEnterpriseTagRef::getTagId).distinct().collect(Collectors.toList());// 用户企业标签

            Long areaTagId = hierarchy.getTagId();//区域标签
            Long areaId = hierarchy.getAreaId();//区域id
            String areaTag = "province_id";
            if (areaTagId == 1) {
                areaTag = "province_id";
            } else if (areaTagId == 2) {
                areaTag = "city_id";
            } else if (areaTagId == 3) {
                areaTag = "district_id";
            } else if (areaTagId == 4) {
                areaTag = "street_id";
            } else if (areaTagId == 5) {
                areaTag = "community_id";
            }

            StringBuilder where = new StringBuilder();
            List<Object> args = new ArrayList<>();
            where.append(" where 1 = 1");

            List<Integer> statusList = new ArrayList<>();
            statusList.add(3);
            //住建局、产权单位：才可查看轮候配租、待配租
            if (enterpriseTagIds.contains(5L) || enterpriseTagIds.contains(2L)) {
                statusList.add(1);
                statusList.add(2);
            }

            //待审批
            List<ApplyAudit> applyAudits = applyAuditRepository.findByAuditStatusAndCurrentAuditId(1, userId);
            List<Long> approveIds = applyAudits.stream().filter(vo -> vo.getApplyId() != null).map(ApplyAudit::getApplyId).distinct().collect(Collectors.toList());
            if (!approveIds.isEmpty()) {
                where.append(" and ( (a." + areaTag + " = ? and a.match_status in " + SqlUtils.foreachIn(statusList.size()) + " )" +
                        " or (a.apply_status in (1,2,10) and a.id in " + SqlUtils.foreachIn(approveIds.size()) + " ) )");
                args.add(areaId);
                args.addAll(statusList);
                args.addAll(approveIds);
            } else {
                where.append(" and ( a." + areaTag + " = ? and a.match_status in " + SqlUtils.foreachIn(statusList.size()) + " )");
                args.add(areaId);
                args.addAll(statusList);
            }

            if (StringUtils.isNotBlank(name)) {
                where.append(" and a.name like ?");
                args.add("%" + name + "%");
            }
            if (type != null) {
                where.append(" and a.type = ?");
                args.add(type);
            }
            if (StringUtils.isNotBlank(applyArea)) {
                where.append(" and a.apply_area like ?");
                args.add("%" + applyArea + "%");
            }
            if (applyStatus != null) {
                where.append(" and a.apply_status = ?");
                args.add(applyStatus);
            }
            if (matchStatus != null) {
                where.append(" and a.match_status = ?");
                args.add(matchStatus);
            }

            // 总记录数
            Long total = jdbcTemplate.queryForObject("SELECT count(1) FROM `saas_house_eligible_apply` a" + where,
                    args.toArray(), Long.class);
            if (total == 0) {
                return resultBean;
            }

            args.add(pageSize);
            args.add(pageNumber * pageSize);
            List<EligibleListVO> list = jdbcTemplate.query(
                    "SELECT a.id,a.match_user_id as matchUserId,a.name,a.type,a.apply_status as applyStatus,a.match_status as matchStatus,\n"
                            + "a.province_id as provinceId,a.city_id as cityId,a.district_id as districtId,a.street_id as streetId,a.community_id as communityId,\n"
                            + "a.apply_time as applyTime FROM `saas_house_eligible_apply` a " + where + ORDER_ORDER + SQL_PAGE,
                    new BeanPropertyRowMapper<>(EligibleListVO.class), args.toArray());

            // 查询申请人名称
            List<String> ids = list.stream().filter(vo -> vo.getMatchUserId() != null)
                    .map(EligibleListVO::getMatchUserId).distinct().collect(Collectors.toList());
            if (!ids.isEmpty()) {
                List<AppUser> appUsers = appUserRepository.findByIdOrEnterpriseIn(ids, ids);
                for (AppUser appUser : appUsers) {
                    for (EligibleListVO vo : list) {
                        if (vo.getMatchUserId() != null && (vo.getMatchUserId().equals(appUser.getId())
                                || vo.getMatchUserId().equals(appUser.getEnterpriseUserId()))) {
                            vo.setMatchUserName(appUser.getName());
                        }
                    }
                }
            }

            // 查询区域名称
            List<Long> areaIds = new ArrayList<>();
            List<Long> provinceIds = list.stream().filter(vo -> vo.getProvinceId() != null).map(EligibleListVO::getProvinceId).distinct().collect(Collectors.toList());
            List<Long> cityIds = list.stream().filter(vo -> vo.getCityId() != null).map(EligibleListVO::getCityId).distinct().collect(Collectors.toList());
            List<Long> districtIds = list.stream().filter(vo -> vo.getDistrictId() != null).map(EligibleListVO::getDistrictId).distinct().collect(Collectors.toList());
            List<Long> streetIds = list.stream().filter(vo -> vo.getStreetId() != null).map(EligibleListVO::getStreetId).distinct().collect(Collectors.toList());
            List<Long> communityIds = list.stream().filter(vo -> vo.getCommunityId() != null).map(EligibleListVO::getCommunityId).distinct().collect(Collectors.toList());
            areaIds.addAll(provinceIds);
            areaIds.addAll(cityIds);
            areaIds.addAll(districtIds);
            areaIds.addAll(streetIds);
            areaIds.addAll(communityIds);
            if (!ids.isEmpty()) {
                Map<Long, String> map = areaRepository.findByIdIn(areaIds).stream().collect(Collectors.toMap(Area::getId, Area::getName));
                if (!map.isEmpty()) {
                    for (EligibleListVO vo : list) {
                        vo.setProvince(map.get(vo.getProvinceId()));
                        vo.setCity(map.get(vo.getCityId()));
                        vo.setDistrict(map.get(vo.getDistrictId()));
                        vo.setStreet(map.get(vo.getStreetId()));
                        vo.setCommunity(map.get(vo.getCommunityId()));
                    }
                }
            }

            for (EligibleListVO vo : list) {
                vo.setApplyTime(DateUtils.format(vo.getApplyTime(), DateUtils.FORMAT_DATETIME_14, DateUtils.FORMAT_DATETIME_14));
            }

            apiData.setData(list);
            apiData.setTotal(total);

            resultBean.setResultData(apiData);
        } catch (Exception e) {
            log.error("ApproveService eligibleList2 Exception = {}" + e.getMessage(), e);
            resultBean.setCode("10001");
            resultBean.setMsg("10001");
        }
        resultBean.setResultData(apiData);
        return resultBean;
    }*/

    /**
     * 企业端-资格审核列表
     *
     * @param accessToken 权限鉴定
     * @param name        申请人
     * @param type        申请类型
     * @param applyArea   申请区域
     * @param pageNumber  当前页
     * @param pageSize    页数
     * @return
     */
    public ResultBean<ApiData<EligibleListVO>> eligibleList2(String accessToken, String name, Integer type, String applyArea,
                                                             Integer applyStatus, Integer matchStatus, Integer pageNumber, Integer pageSize) {
        //创建一个返回对象，设置成功标识
        ResultBean<ApiData<EligibleListVO>> resultBean = new ResultBean<>();
        resultBean.setCode("10000");
        resultBean.setMsg("10000");
        //创建返回对象接收数据
        ApiData<EligibleListVO> apiData = new ApiData<>();
        resultBean.setResultData(apiData);
        try {
            //获取用户登录权限
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            //用户权限的鉴定
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            //获取用户ID
            String userId = tokenRedisVo.getId();
            //获取企业ID
            Long enterpriseId = tokenRedisVo.getEnterpriseId();
            //根据企业ID查询出用户层级权限
            DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
            if (hierarchy == null) {
                return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
            }
            //获取机构层级关系ID
            Long id = hierarchy.getId();
            //根据机构ID查询数据
            List<DepartmentEnterpriseTagRef> refs = departmentEnterpriseTagRefRepository.findByDepRefId(id);
            List<Long> enterpriseTagIds = refs.stream().map(DepartmentEnterpriseTagRef::getTagId).distinct().collect(Collectors.toList());// 用户企业标签
            //获取区域标签ID
            Long areaTagId = hierarchy.getTagId();//区域标签
            //获取区域ID
            Long areaId = hierarchy.getAreaId();//区域id
            String areaTag = "province_id";
            //根据不同区域标签设置对应标签名
            if (areaTagId == 1) {
                areaTag = "province_id";
            } else if (areaTagId == 2) {
                areaTag = "city_id";
            } else if (areaTagId == 3) {
                areaTag = "district_id";
            } else if (areaTagId == 4) {
                areaTag = "street_id";
            } else if (areaTagId == 5) {
                areaTag = "community_id";
            }

            StringBuilder where = new StringBuilder();
            List<Object> args = new ArrayList<>();
            where.append(" where 1 = 1");

            List<Integer> statusList = new ArrayList<>();
            statusList.add(3);
            //住建局、产权单位：才可查看轮候配租、待配租
            if (enterpriseTagIds.contains(5L) || enterpriseTagIds.contains(2L)) {
                statusList.add(1);
                statusList.add(2);
            }

            //待审批
            List<ApplyAudit> applyAudits = applyAuditRepository.findByAuditStatusAndCurrentAuditId(1, userId);
            //获取申请ID
            List<Long> approveIds = applyAudits.stream().filter(vo -> vo.getApplyId() != null).map(ApplyAudit::getApplyId).distinct().collect(Collectors.toList());
            //判断申请ID是否为空
            if (!approveIds.isEmpty()) {
                where.append(" and ( (a." + areaTag + " = ? and a.apply_status = 3 and a.match_status in " + SqlUtils.foreachIn(statusList.size()) + " )" +
                        " or (a.apply_status in (1,2,10) and a.id in " + SqlUtils.foreachIn(approveIds.size()) + " ) )");
                args.add(areaId);
                args.addAll(statusList);
                args.addAll(approveIds);
            } else {
                where.append(" and ( a." + areaTag + " = ? and a.apply_status = 3 and a.match_status in " + SqlUtils.foreachIn(statusList.size()) + " )");
                args.add(areaId);
                args.addAll(statusList);
            }
            //判断前端是否有输入参数
            if (StringUtils.isNotBlank(name)) {
                where.append(" and a.name like ?");
                args.add("%" + name + "%");
            }
            //根据前端传来的惨数，设置对应的值
            if (type != null) {
                where.append(" and a.type = ?");
                args.add(type);
            }
            if (StringUtils.isNotBlank(applyArea)) {
                where.append(" and a.apply_area like ?");
                args.add("%" + applyArea + "%");
            }
            if (applyStatus != null) {
                where.append(" and a.apply_status = ?");
                args.add(applyStatus);
            }
            if (matchStatus != null) {
                where.append(" and a.match_status = ?");
                args.add(matchStatus);
            }
            //获取总数
            String COUNT = "SELECT count(1) ";
            String COLUM = "SELECT a.id,a.match_user_id AS matchUserId,a.name,a.type,a.apply_status AS applyStatus,a.match_status AS matchStatus,\n" +
                    "a.province_id AS provinceId,a.city_id AS cityId,a.district_id AS districtId,a.street_id AS streetId,a.community_id AS communityId,\n" +
                    "a.apply_time AS applyTime,a.dataType ";
            String FROM = " FROM (SELECT a.*,1 AS dataType \n" +
                    "FROM saas_house_eligible_apply a \n" +
                    "UNION ALL \n" +
                    "SELECT a.*,2 AS dataType  \n" +
                    "FROM saas_house_eligible_apply_old a) a ";

            // 总记录数
            Long total = jdbcTemplate.queryForObject(COUNT + FROM + where, args.toArray(), Long.class);
            if (total == 0) {
                return resultBean;
            }
            //设置当前页
            args.add(pageSize);
            //设置页数
            args.add(pageNumber * pageSize);
            //获取数据
            List<EligibleListVO> list = jdbcTemplate.query(COLUM + FROM + where + ORDER_ORDER + SQL_PAGE,
                    new BeanPropertyRowMapper<>(EligibleListVO.class), args.toArray());

            // 查询申请人名称
            List<String> ids = list.stream().filter(vo -> vo.getMatchUserId() != null)
                    .map(EligibleListVO::getMatchUserId).distinct().collect(Collectors.toList());
            //判断是否为空
            if (!ids.isEmpty()) {
                List<AppUser> appUsers = appUserRepository.findByIdOrEnterpriseIn(ids, ids);
                //遍历设置申请人名字
                for (AppUser appUser : appUsers) {
                    for (EligibleListVO vo : list) {
                        if (vo.getMatchUserId() != null && (vo.getMatchUserId().equals(appUser.getId())
                                || vo.getMatchUserId().equals(appUser.getEnterpriseUserId()))) {
                            vo.setMatchUserName(appUser.getName());
                        }
                    }
                }
            }

            // 查询区域名称，获取省、市、区、街道、社区ID
            List<Long> areaIds = new ArrayList<>();
            List<Long> provinceIds = list.stream().filter(vo -> vo.getProvinceId() != null).map(EligibleListVO::getProvinceId).distinct().collect(Collectors.toList());
            List<Long> cityIds = list.stream().filter(vo -> vo.getCityId() != null).map(EligibleListVO::getCityId).distinct().collect(Collectors.toList());
            List<Long> districtIds = list.stream().filter(vo -> vo.getDistrictId() != null).map(EligibleListVO::getDistrictId).distinct().collect(Collectors.toList());
            List<Long> streetIds = list.stream().filter(vo -> vo.getStreetId() != null).map(EligibleListVO::getStreetId).distinct().collect(Collectors.toList());
            List<Long> communityIds = list.stream().filter(vo -> vo.getCommunityId() != null).map(EligibleListVO::getCommunityId).distinct().collect(Collectors.toList());
            //添加省、市、区、街道、社区ID
            areaIds.addAll(provinceIds);
            areaIds.addAll(cityIds);
            areaIds.addAll(districtIds);
            areaIds.addAll(streetIds);
            areaIds.addAll(communityIds);
            if (!ids.isEmpty()) {
                Map<Long, String> map = areaRepository.findByIdIn(areaIds).stream().collect(Collectors.toMap(Area::getId, Area::getName));
                if (!map.isEmpty()) {
                    for (EligibleListVO vo : list) {
                        vo.setProvince(map.get(vo.getProvinceId()));
                        vo.setCity(map.get(vo.getCityId()));
                        vo.setDistrict(map.get(vo.getDistrictId()));
                        vo.setStreet(map.get(vo.getStreetId()));
                        vo.setCommunity(map.get(vo.getCommunityId()));
                    }
                }
            }
            //遍历循环设置申请时间
            for (EligibleListVO vo : list) {
                vo.setApplyTime(DateUtils.format(vo.getApplyTime(), DateUtils.FORMAT_DATETIME_14, DateUtils.FORMAT_DATETIME_14));
            }
            //设置数据和总数
            apiData.setData(list);
            apiData.setTotal(total);
            //把数据返回给前端页面
            resultBean.setResultData(apiData);
        } catch (Exception e) {
            //记录报错日志
            log.error("ApproveService eligibleList2 Exception = {}" + e.getMessage(), e);
            resultBean.setCode("10001");
            resultBean.setMsg("10001");
        }
        //把数据返回给前端页面
        resultBean.setResultData(apiData);
        return resultBean;
    }
    /**
     * 审批按钮状态,实现了判断数据是否是0：按钮可审批，1：按钮不可审批，2：按钮已审批
     *
     * @param accessToken 权限鉴定
     * @param applyId 申请ID
     * @return
     */
    public ResultBean<Integer> approveStatus(String accessToken, Long applyId, Integer type) {
        try {
            //记录操作日志
            log.info("ApproveService approveStatus, applyId={}, type={}", applyId, type);
            //获取用户登录权限
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            //用户权限的鉴定
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            //获取用户ID
            String userId = tokenRedisVo.getId();// 用户id

            Integer status = null;// 状态标识

            if (type == null || type == 1) {
                // 查询待审批流程
                ApplyAudit audit = applyAuditRepository.findByApplyIdAndAuditStatusAndCurrentAuditId(applyId,
                        ApplyAuditTypeEnum.APPROVE_PENDING.getValue(), userId);
                if (audit != null) {
                    status = 0;// 按钮可审批
                } else {
                    // 查询已审批流程
                    List<ApplyAudit> approved = applyAuditRepository.findApproved(applyId, userId);
                    if (approved != null && approved.size() != 0) {
                        status = 2;// 按钮已审批
                    } else {
                        status = 1;// 按钮不可审批
                    }
                }
            } else {
                // 查询待审批流程
                ApplyAuditOld audit = applyAuditOldRepository.findByApplyIdAndAuditStatusAndCurrentAuditId(applyId,
                        ApplyAuditTypeEnum.APPROVE_PENDING.getValue(), userId);
                if (audit != null) {
                    status = 0;// 按钮可审批
                } else {
                    // 查询已审批流程
                    List<ApplyAuditOld> approved = applyAuditOldRepository.findApproved(applyId, userId);
                    if (approved != null && approved.size() != 0) {
                        status = 2;// 按钮已审批
                    } else {
                        status = 1;// 按钮不可审批
                    }
                }
            }
            //把判断结果返回给前端
            return ResultBean.successfulResult(status);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }
    /**
     * 审批操作,实现了手动进行公租房的审批流程
     *
     * @param applyId 申请ID
     * @param auditStatus 0未审批 1待审批 2审批通过 3审批不通过
     * @param remark 审批备注
     * @return
     */
    @Transactional
    public ResultBean<Object> approveEligible(String accessToken, Long applyId, Integer auditStatus, String remark) {
        try {
            //记录操作日志
            log.info("ApproveService approveEligible, applyId={}, auditStatus={}, remark={}", applyId, auditStatus, remark);
            //获取用户登录权限
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            //用户权限的鉴定
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            //获取用户ID
            String userId = tokenRedisVo.getId();
            //获取企业ID
            Long enterpriseId = tokenRedisVo.getEnterpriseId();
            //判断申请信息
            if (applyId == null) {
                return ResultBean.failedResultOfParamWithMsg("申请id为空");
            }
            if (auditStatus == null) {
                return ResultBean.failedResultOfParamWithMsg("审批状态id为空");
            }
            if (auditStatus == ApplyAuditTypeEnum.NOT_APPROVE.getValue() && StringUtils.isBlank(remark)) {
                return ResultBean.failedResultOfParamWithMsg("审批原因为空");
            }
            //根据申请ID获取申请资格数据
            Optional<Eligible> eligibleOpt = eligibleRepository.findById(applyId);
            if (!eligibleOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("资格申请不存在");
            }
            Eligible eligible = eligibleOpt.get();
            Date date = new Date();

            //修改待审批流程
            List<ApplyAudit> audits = applyAuditRepository.findByApplyIdAndCurrentAuditIdAndAuditStatus(applyId, userId, ApplyAuditTypeEnum.APPROVE_PENDING.getValue());
            if (audits.isEmpty()) {
                return ResultBean.failedResultWithMsg("已审批的申请不能再次审批");
            }
            //获取审批数据
            ApplyAudit audit = audits.get(0);
            ApprovalProcessUser approvalProcessUser = approvalProcessUserRepository.findByAreaIdAndStatus(audit.getOrgAreaId(), 1);
            if (approvalProcessUser == null) {
                return ResultBean.failedResultWithMsg("资格审批人状态已禁用，无法审批");
            }
            //修改保存审批的数据
            audit.setAuditStatus(auditStatus);
            audit.setRemark(remark);
            audit.setAuditTime(date);
            applyAuditRepository.save(audit);
            //修改待办事项状态
            List<BacklogItemApprove> approves = backlogItemApproveRepository.findByApplyAuditIdAndStatus(audit.getId(), 0);
            if (!approves.isEmpty()) {
                BacklogItemApprove approve = approves.get(0);
                approve.setStatus(1);
                backlogItemApproveRepository.save(approve);

                Optional<BacklogItem> backlogItemOpt = backlogItemRepository.findById(approve.getBacklogItemId());
                if (!backlogItemOpt.isPresent()) {
                    return ResultBean.failedResultWithMsg("待办事项不存在");
                }
                BacklogItem backlogItem = backlogItemOpt.get();
                backlogItem.setBusinessStatus("已审批");
                backlogItem.setHandleStatus(1);
                backlogItem.setHandlerTime(date);
                backlogItemRepository.save(backlogItem);
            }

            HousePutRecords records = housePutRecordsRepository.findByApplyId(applyId);
            //资格审批
            if (records == null) {
                if (auditStatus == ApplyAuditTypeEnum.APPROVE.getValue()) {// 审批通过
                    List<ApplyAudit> list = applyAuditRepository.findByApplyIdAndAuditStatus(applyId, ApplyAuditTypeEnum.YET_APPROVE.getValue());
                    if (list != null && list.size() != 0) {// 有未审批
                        eligibleRepository.updateById(applyId, EligibleApplyTypeEnum.APPROVING.getValue());
                        //审批通过，将下一流程状态改成待审批
                        ApplyAudit applyAudit = list.get(0);
                        applyAudit.setAuditStatus(ApplyAuditTypeEnum.APPROVE_PENDING.getValue());
                        applyAuditRepository.save(applyAudit);

                        //生成下一个审批人资格审批待办事项
                        if (applyAudit.getCurrentAuditId() != null) {
                            BacklogItem backlogItem = new BacklogItem();
                            backlogItem.setType(BacklogItemTypeEnum.ELIGIBLE_APPROVE.getValue());
                            backlogItem.setTitle(eligible.getName() + "提交的公租房资格申请");
                            backlogItem.setBusinessStatus("待审批");
                            backlogItem.setHandleStatus(0);
                            backlogItem.setOperatorId(eligible.getMatchUserId());
                            backlogItem.setCreateTime(date);
                            BacklogItem save = backlogItemRepository.save(backlogItem);

                            BacklogItemApprove backlogItemApprove = new BacklogItemApprove();
                            backlogItemApprove.setBacklogItemId(save.getId());
                            backlogItemApprove.setApplyId(applyId);
                            backlogItemApprove.setApplyAuditId(applyAudit.getId());
                            backlogItemApprove.setUserId(applyAudit.getCurrentAuditId());
                            backlogItemApprove.setStatus(0);
                            backlogItemApproveRepository.save(backlogItemApprove);
                        }
                    } else {// 没有未审批
                        eligibleRepository.updateById(applyId, EligibleApplyTypeEnum.APPROVE.getValue());
                        eligibleRepository.updateMatchStatus(applyId, EligibleMatchTypeEnum.WAIT_RENT.getValue());
                        //生成轮候配租待办事项
                        BacklogItem backlogItem = new BacklogItem();
                        backlogItem.setOrgId(enterpriseId);
                        backlogItem.setType(BacklogItemTypeEnum.WAIT_RENT.getValue());
                        backlogItem.setTitle(eligible.getName() + "申请的公租房待轮候配租");
                        backlogItem.setContent("配租描述：请尽快轮候配租。");
                        backlogItem.setBusinessStatus("待轮候配租");
                        backlogItem.setHandleStatus(0);
                        backlogItem.setOperatorId(userId);
                        backlogItem.setCreateTime(date);
                        BacklogItem save = backlogItemRepository.save(backlogItem);

                        BacklogItemWaitRent backlogItemWaitRent = new BacklogItemWaitRent();
                        backlogItemWaitRent.setBacklogItemId(save.getId());
                        backlogItemWaitRent.setApplyId(applyId);
                        backlogItemWaitRentRepository.save(backlogItemWaitRent);
                    }
                } else {// 审批不通过，不修改下一审批流程
                    eligibleRepository.updateById(applyId, EligibleApplyTypeEnum.NOT_APPROVE.getValue());
                    //审批不通过发送短信
                    smsService.sendTemplateNopassSms(eligible.getMobile());
                }
            }

            //备案变更审批
            if (records != null) {
                String houseId = records.getHouseId();
                Optional<House> houseOpt = houseRepository.findById(houseId);
                House house = houseOpt.get();
                if (!houseOpt.isPresent()) {
                    return ResultBean.failedResultWithMsg("公租房不存在");
                }

                if (auditStatus == ApplyAuditTypeEnum.APPROVE.getValue()) {// 审批通过
                    List<ApplyAudit> list = applyAuditRepository.findByApplyIdAndAuditStatus(applyId, ApplyAuditTypeEnum.YET_APPROVE.getValue());
                    if (list != null && list.size() != 0) {// 有未审批
                        //审批通过，将下一流程状态改成待审批
                        ApplyAudit applyAudit = list.get(0);
                        applyAudit.setAuditStatus(ApplyAuditTypeEnum.APPROVE_PENDING.getValue());
                        applyAuditRepository.save(applyAudit);

                        //生成下一个审批人资格审批待办事项
                        if (applyAudit.getCurrentAuditId() != null) {
                            BacklogItem backlogItem = new BacklogItem();
                            backlogItem.setType(BacklogItemTypeEnum.ELIGIBLE_APPROVE.getValue());
                            backlogItem.setTitle(eligible.getName() + "提交的公租房备案变更");
                            backlogItem.setBusinessStatus("待审批");
                            backlogItem.setHandleStatus(0);
                            backlogItem.setOperatorId(eligible.getMatchUserId());
                            backlogItem.setCreateTime(date);
                            backlogItem.setApplyType(2);
                            BacklogItem save = backlogItemRepository.save(backlogItem);

                            BacklogItemApprove backlogItemApprove = new BacklogItemApprove();
                            backlogItemApprove.setBacklogItemId(save.getId());
                            backlogItemApprove.setApplyId(applyId);
                            backlogItemApprove.setApplyAuditId(applyAudit.getId());
                            backlogItemApprove.setUserId(applyAudit.getCurrentAuditId());
                            backlogItemApprove.setStatus(0);
                            backlogItemApproveRepository.save(backlogItemApprove);
                        }
                    } else {// 没有未审批
                        List<String> delIds = cohabitRepository.findByApplyIdAndStatusOrderByApplyTimeAsc(applyId, CohabitStatusEnum.DEL.getValue()).stream().
                                map(Cohabit::getId).distinct().collect(Collectors.toList());
                        if (delIds != null && !delIds.isEmpty()) {
                            //删除智能锁授权，表数据
                            for (String delId : delIds) {
                                List<SmartLockAuth> auth = smartLockAuthRepository.findByAuthorUserId(delId);
                                if (CollectionUtil.isNotEmpty(auth)) {
                                    Long lockAuthId = auth.get(0).getId();
                                    //删除用户授权
                                    lockAppService.delPersonAuth(lockAuthId);
                                    //删除表数据
                                    smartLockAuthRepository.deleteById(lockAuthId);
                                    smartLockPwdRepository.deleteByLockAuthId(lockAuthId);
                                    smartLockCardRepository.deleteByLockAuthId(lockAuthId);
                                    smartLockFingerprintRepository.deleteByLockAuthId(lockAuthId);
                                }
                            }
                            //删除同住人
                            cohabitRepository.deleteByIdIn(delIds);
                        }

                        List<Cohabit> cohabits = cohabitRepository.findByApplyIdAndStatusOrderByApplyTimeAsc(applyId, CohabitStatusEnum.SAVE.getValue());
                        if (cohabits != null && !cohabits.isEmpty()) {
                            //更新新增为正常状态
                            cohabitRepository.updateStatusByApplyIdAndStatus(applyId, CohabitStatusEnum.SAVE.getValue(), CohabitStatusEnum.NORMAL.getValue());
                            //新增智能锁授权用户
                            List<SmartLock> locks = smartLockRepository.findByHouseId(houseId);
                            if (!locks.isEmpty()) {
                                SmartLock smartLock = locks.get(0);
                                for (Cohabit cohabit : cohabits) {
                                    SmartLockAuth cohabitAuth = new SmartLockAuth();
                                    cohabitAuth.setLockId(smartLock.getId());
                                    cohabitAuth.setHouseId(houseId);
                                    cohabitAuth.setBindType(0);//单位
                                    cohabitAuth.setMatchUserId(eligible.getMatchUserId());
                                    cohabitAuth.setAuthorUserId(cohabit.getId());
                                    cohabitAuth.setUserName(cohabit.getName());
                                    cohabitAuth.setMobile(cohabit.getMobile());
                                    cohabitAuth.setRelationTag(cohabit.getFamilyTiesType());
                                    cohabitAuth.setPwdStatus(0);
                                    cohabitAuth.setFingerprintStatus(0);
                                    cohabitAuth.setCardStatus(0);
                                    cohabitAuth.setCpuStatus(0);
                                    cohabitAuth.setBleStatus(0);
                                    cohabitAuth.setCreateTime(date);
                                    cohabitAuth.setUserType(2);
                                    smartLockAuthRepository.save(cohabitAuth);
                                }
                            }
                        }

                        //修改公租房备案信息变更状态为：已完成
                        house.setRecordChangeStatus(RecordChangeStatusEnum.DONE.getValue());
                        houseRepository.save(house);

                        //修改资格申请状态
                        eligible.setApplyStatus(EligibleApplyTypeEnum.APPROVE.getValue());
                        eligibleRepository.save(eligible);
                    }
                } else {// 审批不通过
                    //恢复填写流程，恢复同住人状态
                    List<String> delIds = cohabitRepository.findByApplyIdAndStatusOrderByApplyTimeAsc(applyId, CohabitStatusEnum.DEL.getValue()).stream().
                            map(Cohabit::getId).distinct().collect(Collectors.toList());
                    List<String> saveIds = cohabitRepository.findByApplyIdAndStatusOrderByApplyTimeAsc(applyId, CohabitStatusEnum.SAVE.getValue()).stream().
                            map(Cohabit::getId).distinct().collect(Collectors.toList());
                    resetApplyFlow(applyId, delIds, saveIds);

                    //修改公租房备案信息变更状态为：未变更
                    house.setRecordChangeStatus(RecordChangeStatusEnum.NOCHANGE.getValue());
                    houseRepository.save(house);

                    //修改资格申请状态
                    eligible.setApplyStatus(EligibleApplyTypeEnum.APPROVE.getValue());
                    eligibleRepository.save(eligible);
                }
            }

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public void resetApplyFlow(Long applyId, List<String> delIds, List<String> saveIds) {
        if (saveIds != null && !saveIds.isEmpty()) {
            //更新申请资料填写流程
            for (String saveId : saveIds) {
                HouseApplyFlow flow = houseApplyFlowRepository.findByDataId(saveId);
                String upDataId = flow.getUpDataId();
                String nextDataId = flow.getNextDataId();

                //更新上一流程
                houseApplyFlowRepository.updateByDataId(upDataId, nextDataId);
                //更新下一流程
                if (StringUtils.isNotBlank(nextDataId)) {
                    houseApplyFlowRepository.updateNextDataIdByDataId(nextDataId, upDataId);
                }
                //删除流程
                houseApplyFlowRepository.deleteByDataId(saveId);
            }

            //删除新增同住人
            cohabitRepository.deleteByIdIn(saveIds);
        }

        if (delIds != null && !delIds.isEmpty()) {
            //获取填写流程最后同住人
            List<Cohabit> cohabits = cohabitRepository.findByApplyIdAndStatusOrderByApplyTimeDesc(applyId, CohabitStatusEnum.NORMAL.getValue());
            HouseApplyFlow flow = null;
            String applyCode = null;
            String dataId = null;
            if (!cohabits.isEmpty()) {//有同住人
                String cohabitId = cohabits.get(0).getId();
                flow = houseApplyFlowRepository.findByDataId(cohabitId);
                applyCode = flow.getApplyCode();
                dataId = cohabitId;
            } else {//没有同住人
                flow = houseApplyFlowRepository.findByDataId(applyId.toString());
                applyCode = flow.getApplyCode();
                dataId = applyId.toString();
            }

            List<Cohabit> saveCohabits = cohabitRepository.findByIdInOrderByApplyTimeAsc(delIds);
            for (Cohabit saveCohabit : saveCohabits) {
                String saveCohabitId = saveCohabit.getId();
                int index = saveCohabits.indexOf(saveCohabit);
                if (index == 0) {
                    //新增流程数据
                    HouseApplyFlow applyFlow = new HouseApplyFlow();
                    applyFlow.setApplyCode(applyCode);
                    applyFlow.setType(2);
                    applyFlow.setDataId(saveCohabitId);
                    applyFlow.setUpDataId(dataId);
                    houseApplyFlowRepository.save(applyFlow);
                    //更新上一流程
                    flow.setNextDataId(saveCohabitId);
                    houseApplyFlowRepository.save(flow);
                } else {
                    //上一新增同住人
                    Cohabit cohabit = saveCohabits.get(--index);
                    HouseApplyFlow upFlow = houseApplyFlowRepository.findByDataId(cohabit.getId());
                    //新增流程数据
                    HouseApplyFlow applyFlow = new HouseApplyFlow();
                    applyFlow.setApplyCode(applyCode);
                    applyFlow.setType(2);
                    applyFlow.setDataId(saveCohabitId);
                    applyFlow.setUpDataId(cohabit.getId());
                    houseApplyFlowRepository.save(applyFlow);
                    //更新上一流程
                    upFlow.setNextDataId(saveCohabitId);
                    houseApplyFlowRepository.save(upFlow);
                }
            }
            //删除同住人改成正常状态
            cohabitRepository.updateStatusByIdIn(delIds, CohabitStatusEnum.NORMAL.getValue());
        }
    }
    /**
     * 轮候配租列表
     *
     * @param accessToken 权限鉴定
     * @param applyId 申请ID
     * @param backlogItemId 待办事项ID
     * @return
     */
    public ResultBean<WaitingRentDataVO<WaitingRentVO>> waitingRent(String accessToken, Long applyId, Long backlogItemId) {
        log.info("ApproveService waitingRent, applyId={}, backlogItemId={}", applyId, backlogItemId);
        try {
            WaitingRentDataVO<WaitingRentVO> dataVO = new WaitingRentDataVO<>();

            Long districtId = 0L;
            String applyCode = null;
            if (applyId != null) {
                //根据申请ID查询申请资格表
                Optional<Eligible> eligibleOpt = eligibleRepository.findById(applyId);
                if (!eligibleOpt.isPresent()) {
                	log.info("轮候配租, 资格申请不存在, applyId={}", applyId);
                    return ResultBean.failedResultWithMsg("资格申请不存在");
                }
                //获取申请资格表属性
                Eligible eligible = eligibleOpt.get();
                districtId = eligible.getDistrictId();
                //设置属性
                dataVO.setApplyId(applyId);
                dataVO.setDistrictId(districtId);
                dataVO.setMatchUserId(eligible.getMatchUserId());
                dataVO.setMatchUserName(eligible.getName());
                applyCode = eligible.getApplyCode();
            }
            //判断待办事项是否存储
            if (backlogItemId != null) {
                BacklogItemWaitRent backlogItemWaitRent = backlogItemWaitRentRepository.findByBacklogItemId(backlogItemId);
                if (backlogItemWaitRent == null) {
                	log.info("轮候配租, 待办事项参数数据不存在, applyId={}, backlogItemId={}", applyId, backlogItemId);
                    return ResultBean.failedResultWithMsg("待办事项参数数据不存在");
                }
                Optional<Eligible> eligibleOpt = eligibleRepository.findById(backlogItemWaitRent.getApplyId());
                if (!eligibleOpt.isPresent()) {
                    return ResultBean.failedResultWithMsg("资格申请不存在");
                }
                Eligible eligible = eligibleOpt.get();
                districtId = eligible.getDistrictId();

                dataVO.setApplyId(eligible.getId());
                dataVO.setDistrictId(districtId);
                dataVO.setMatchUserId(eligible.getMatchUserId());
                dataVO.setMatchUserName(eligible.getName());
            }

            if (applyCode == null) {
                String sql = "select h.org_id as orgId , d.name as orgName,\n"
                        + "sum(CASE WHEN h.match_status = 0 OR h.match_status = 1 THEN 1 ELSE 0 END) as sum\n"
                        + "from  saas_house h left join saas_department d on h.org_id = d.id \n"
                        + "where h.district_id = ? and h.bind_status = 1 AND h.audit_status = 1 and h.house_nature = 1\n"
                        + "group by  h.org_id";
                List<WaitingRentVO> data = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(WaitingRentVO.class), districtId);
                dataVO.setData(data);
            } else {
                // 多承租人，已配租的公租房，按批次号查询，相同批次的资格申请可重复配租同一个公租房
                String sql = "SELECT h.org_id AS orgId , d.name AS orgName, COUNT(1) AS SUM "
                        + "FROM  saas_house h LEFT JOIN saas_department d ON h.org_id = d.id "
                        + "WHERE h.district_id = ? AND h.bind_status = 1 AND h.audit_status = 1 AND h.house_nature = 1 AND "
                        + "((h.match_status = 0 OR h.match_status = 1) OR (h.match_status = 2 AND h.apply_code = ?)) "
                        + "GROUP BY  h.org_id";
                List<WaitingRentVO> data = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(WaitingRentVO.class), districtId, applyCode);
                dataVO.setData(data);
            }

            return ResultBean.successfulResult(dataVO);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<WaitingRentVO> backlogWaitingRent(String accessToken, Long backlogItemId) {
        log.info("ApproveService waitingRent, backlogItemId={}", backlogItemId);
        try {
            WaitingRentVO vo = new WaitingRentVO();

            BacklogItemWaitRent backlogItemWaitRent = backlogItemWaitRentRepository.findByBacklogItemId(backlogItemId);
            if (backlogItemWaitRent == null) {
                return ResultBean.failedResultWithMsg("待办事项参数数据不存在");
            }
            Long applyId = backlogItemWaitRent.getApplyId();

            WaitingRentRecord record = waitingRentRecordRepository.findByApplyId(applyId);
            Long orgId = record.getOrgId();
            String residenceCommunityId = record.getResidenceCommunityId();
            String orgName = null;
            String residenceCommunityName = null;

            Optional<Department> departmentOptional = departmentRepository.findById(orgId);
            if (departmentOptional.isPresent()) {
                Department department = departmentOptional.get();
                orgName = department.getName();
            }

            Optional<Community> communityOptional = communityRepository.findById(residenceCommunityId);
            if (communityOptional.isPresent()) {
                Community community = communityOptional.get();
                residenceCommunityName = community.getName();
            }

            vo.setOrgId(orgId);
            vo.setOrgName(orgName);
            vo.setResidenceCommunityId(residenceCommunityId);
            vo.setResidenceCommunityName(residenceCommunityName);

            return ResultBean.successfulResult(vo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<List<Map<String, Object>>> emptyHouse(Long orgId, Long districtId, Long applyId) {
        try {
            log.info("ApproveService emptyHouse, orgId={}, districtId={}, applyId={}", orgId, districtId, applyId);
            if (orgId == null) {
                return ResultBean.failedResultOfParamWithMsg("产权人id为空");
            }

            if (districtId == null) {
                return ResultBean.failedResultOfParamWithMsg("区id为空");
            }

            String applyCode = null;
            if (applyId != null) {
                Optional<Eligible> eligibleOpt = eligibleRepository.findById(applyId);
                if (!eligibleOpt.isPresent()) {
                    return ResultBean.failedResultWithMsg("资格申请不存在");
                }
                Eligible eligible = eligibleOpt.get();
                applyCode = eligible.getApplyCode();
            }

            List<Map<String, Object>> list = new ArrayList<>();
            if (applyCode == null) {
                String sql = "SELECT h.residence_community_id AS residenceCommunityId,c.name AS residenceCommunityName,\n"
                        + "SUM(CASE WHEN h.match_status = 0 OR h.match_status = 1 THEN 1 ELSE 0 END) AS SUM,a1.name AS streetName,a2.name AS communityName\n"
                        + "FROM  saas_house h LEFT JOIN saas_community c ON h.residence_community_id = c.id\n"
                        + "LEFT JOIN `sys_area` a1 ON a1.id = h.`street_id` LEFT JOIN `sys_area` a2 ON a2.id = h.`community_id`\n"
                        + "WHERE h.org_id = ? AND h.district_id = ? AND h.audit_status = 1 and h.house_nature = 1\n"
                        + "GROUP BY  h.residence_community_id";
                list = jdbcTemplate.queryForList(sql, orgId, districtId);
            } else {
                // 多承租人模式，支持同批次资格申请，可以配租同一个公租房
                String sql = "SELECT h.residence_community_id AS residenceCommunityId,c.name AS residenceCommunityName,COUNT(1) AS SUM,\n"
                        + "a1.name AS streetName,a2.name AS communityName\n"
                        + "FROM  saas_house h LEFT JOIN saas_community c ON h.residence_community_id = c.id\n"
                        + "LEFT JOIN `sys_area` a1 ON a1.id = h.`street_id` LEFT JOIN `sys_area` a2 ON a2.id = h.`community_id`\n"
                        + "WHERE h.org_id = ? AND h.district_id = ? AND h.audit_status = 1 AND h.house_nature = 1\n"
                        + "AND ((h.match_status = 0 OR h.match_status = 1) OR (h.match_status = 2 AND h.apply_code = ?))\n"
                        + "GROUP BY  h.residence_community_id";
                list = jdbcTemplate.queryForList(sql, orgId, districtId, applyCode);
            }

            return ResultBean.successfulResult(list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public ResultBean<Object> rent(String accessToken, Long applyId, String matchUserId, Long orgId,
                                   String residenceCommunityId) throws CustomException {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();// 用户id
            Long enterpriseId = tokenRedisVo.getEnterpriseId();

            if (applyId == null) {
                return ResultBean.failedResultOfParamWithMsg("申请id为空");
            }
            if (StringUtils.isBlank(matchUserId)) {
                return ResultBean.failedResultOfParamWithMsg("承租人id为空");
            }
            if (orgId == null) {
                return ResultBean.failedResultOfParamWithMsg("产权人id为空");
            }
            if (StringUtils.isBlank(residenceCommunityId)) {
                return ResultBean.failedResultOfParamWithMsg("小区id为空");
            }

            AppUser user = appUserRepository.findByIdOrEnterpriseUserId(matchUserId, matchUserId);
            if (user == null) {
                return ResultBean.failedResultWithMsg("申请人未注册APP账户");
            }

            //生成轮候配租记录
            List<WaitingRentRecord> recordList = waitingRentRecordRepository.findByApplyIdAndMatchUserId(applyId, matchUserId);
            if (!recordList.isEmpty()) {
                return ResultBean.failedResultWithMsg("申请人已存在轮候配租信息, 不可重复操作");
            }
            Date date = new Date();
            WaitingRentRecord record = new WaitingRentRecord();
            record.setApplyId(applyId);
            record.setMatchUserId(matchUserId);
            record.setOrgId(orgId);
            record.setResidenceCommunityId(residenceCommunityId);
            record.setStatus(0);// 未配租
            record.setOperationId(userId);
            record.setOperationTime(date);
            waitingRentRecordRepository.save(record);

            //资格申请状态改成待配租
            eligibleRepository.updateMatchStatus(applyId, EligibleMatchTypeEnum.YET_RENT.getValue());
            //该小区所有未配租房改成可配租
            houseRepository.updateMatchStatus(residenceCommunityId, orgId, HouseMatchStatusEnum.NOT_RENT.getValue(), HouseMatchStatusEnum.CAN_RENT.getValue());

            //修改轮候配租待办事项状态
            BacklogItemWaitRent backlogItemWaitRent = backlogItemWaitRentRepository.findByApplyId(applyId);
            if (backlogItemWaitRent != null) {
                Optional<BacklogItem> backlogItemOpt = backlogItemRepository.findById(backlogItemWaitRent.getBacklogItemId());
                if (!backlogItemOpt.isPresent()) {
                	log.info("待办事项不存在, BacklogItemId={}", backlogItemWaitRent.getBacklogItemId());
                    throw new CustomException("待办事项不存在");
                }
                BacklogItem item = backlogItemOpt.get();
                item.setBusinessStatus("已轮候配租");
                item.setHandleStatus(1);
                item.setHandlerTime(date);
                backlogItemRepository.save(item);
            }

            AppUser appUsers = null;
            if (StringUtils.isNotBlank(matchUserId)){
                 appUsers = appUserRepository.findByIdOrEnterpriseUserId(matchUserId, matchUserId);
            }
            //生成配租待办事项
            BacklogItem backlogItem = new BacklogItem();
            backlogItem.setOrgId(orgId);//产权单位id
            backlogItem.setUserOrgId(enterpriseId);
            backlogItem.setType(BacklogItemTypeEnum.RENT.getValue());
            backlogItem.setTitle(user.getName() + "申请的公租房待配租");
            backlogItem.setContent("配租描述：请尽快配租。");
            backlogItem.setBusinessStatus("待配租");
            backlogItem.setHandleStatus(0);//0未读/未处理
            backlogItem.setOperatorId(userId);
            backlogItem.setMatchUserId(matchUserId);

            backlogItem.setCreateTime(date);
            BacklogItem save = backlogItemRepository.save(backlogItem);

            BacklogItemRent backlogItemRent = new BacklogItemRent();
            backlogItemRent.setBacklogItemId(save.getId());
            backlogItemRent.setApplyId(applyId);
            backlogItemRent.setOrgId(orgId);
            backlogItemRent.setResidenceCommunityId(residenceCommunityId);
            backlogItemRent.setMatchUserId(matchUserId);
            backlogItemRentRepository.save(backlogItemRent);

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new CustomException("系统异常, 请联系管理员!");
        }
    }
    /**
     * 轮候配租按钮状态，实现了判断数据0:可轮候配租，1:不可轮候配租
     *
     * @param accessToken 权限鉴定
     * @return
     */
    public ResultBean<Integer> waitingRentStatus(String accessToken) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            Long enterpriseId = tokenRedisVo.getEnterpriseId();// 顶级部门id

            // 根据机构id 查 标签id
            DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
            if (hierarchy == null) {
                return ResultBean.failedResultWithMsg("用户所属机构未设置层级关系");
            }
            Long tagId = hierarchy.getTagId();

            Integer status;
            List<DepartmentEnterpriseTagRef> d = departmentEnterpriseTagRefRepository.findByDepRefId(hierarchy.getId());
            List<Long> tag = d.stream().map(DepartmentEnterpriseTagRef::getTagId).collect(Collectors.toList());
            if (tag.contains(5L)) {// 可轮候配租
                status = 0;
            } else {
                status = 1;
            }

            return ResultBean.successfulResult(status);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<HouseInfoVO> findHouse(String accessToken, Long applyId) {
        try {
            if (applyId == null) {
                return ResultBean.failedResultOfParamWithMsg("申请id为空");
            }

            HouseMatchUser houseMatchUser = houseMatchUserRepository.findByApplyIdAndStatus(applyId, 1);
            if (houseMatchUser == null) {
                return ResultBean.failedResultWithMsg("配租记录不存在");
            }
            String houseId = houseMatchUser.getHouseId();

            ResultBean<HouseInfoVO> resultBean = houseService.findHouse(houseId);
            HouseInfoVO vo = resultBean.getResultData();

            return ResultBean.successfulResult(vo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    @Transactional
    public ResultBean<Object> batchApprove(String accessToken, BatchApproveVO vo) {
        try {
            List<Long> applyIds = vo.getApplyIds();
            Integer auditStatus = vo.getAuditStatus();
            String remark = vo.getRemark();

            if (applyIds.isEmpty()) {
                return ResultBean.failedResultOfParamWithMsg("申请id为空");
            }
            if (auditStatus == null) {
                return ResultBean.failedResultOfParamWithMsg("审批状态为空");
            }
            if (auditStatus == ApplyAuditTypeEnum.NOT_APPROVE.getValue() && StringUtils.isBlank(remark)) {
                return ResultBean.failedResultOfParamWithMsg("审批原因为空");
            }

            for (Long applyId : applyIds) {
                ResultBean<Object> resultBean = approveEligible(accessToken, applyId, auditStatus, remark);
                String code = resultBean.getCode();
                String msg = resultBean.getMsg();
                if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                    return ResultBean.failedResultWithMsg(msg);
                }
            }

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


}
